﻿using System.Collections.Generic;
using System.Linq;
using Configuration;
using Model;
using Repository.Common;

namespace Repository
{
    public class ImageRepository : Repository<Image>
    {
        public ImageRepository(Database context)
            : base(context)
        {
        }

        public List<Image> GetByProductId(int productId)
        {
            GetContext().ContextOptions.LazyLoadingEnabled = true;

            var res = from r in GetQuery().Include("Product").OrderBy(o => o.Id) where r.Product.Id == productId select r;

            return res.ToList();
        }

        public string GetImageByProductID(int productId)
        {
            var res = (from r in GetQuery().OrderBy(o => o.Id)
                       where r.IsAvatar == true && r.Product.Id == productId
                       select r.Url).FirstOrDefault();

            return res;
        }

        public Image GetByIdHaveProduct(int id)
        {
            GetContext().ContextOptions.LazyLoadingEnabled = true;

            var res = (from r in GetQuery().Include("Product").OrderBy(o => o.Id) where r.Id == id select r).SingleOrDefault();

            return res;
        }

        public int GetTotalPage(int productId, int numOfRows)
        {
            GetContext().ContextOptions.LazyLoadingEnabled = true;

            var res = from r in GetQuery().Include("Product").OrderBy(o => o.Id) where r.Product.Id == productId select r;

            return base.GetTotalPage(numOfRows, res.ToList());
            //return Convert.ToInt32((double)res.Count() / numOfRows) + 1;
        }

        public List<Image> Paging(int productId, int pageIndex, int numOfRows)
        {
            var skipRows = (pageIndex - 1) * numOfRows;

            return GetByProductId(productId).Skip(skipRows).Take(numOfRows).ToList();
        }
    }
}